import SockJS from "sockjs-client";
import Stomp from "webstomp-client";
export default {
  name: "websocket",
  data: function() {
    return {
      websocket: {
        received_messages: [],
        send_message: null,
        connected: false
      }
    };
  },
  methods: {
    send() {
      // console.log("Send message:" + this.send_message);
      if (this.stompClient && this.stompClient.connected) {
        const msg = { name: this.send_message };
        this.stompClient.send("/app/result", JSON.stringify(msg), {});
      }
    },
    connect() {
      let self = this;
      this.socket = new SockJS(
        `http://${process.env.VUE_APP_BACKEND_URL}:8080/chinanet`
      );
      this.stompClient = Stomp.over(this.socket);
      this.stompClient.connect(
        {},
        frame => {
          self.connected = true;
          //console.log(frame);
          self.stompClient.subscribe("/topic/model", async tick => {
            //console.log("接收到消息");
            self.websocket.received_messages.push(JSON.parse(tick.body));
            let notification = new Notification("执行完成", {
              body: "执行完成,点击查看结果"
            });
            // 生成通知消息
            let key = JSON.parse(tick.body).operationId;
          });
        },
        error => {
          //console.log(error);
          this.connected = false;
        }
      );
    },
    disconnect() {
      if (this.stompClient) {
        this.stompClient.disconnect();
      }
      this.connected = false;
    },
    tickleConnection() {
      this.connected ? this.disconnect() : this.connect();
    }
  }
};
